package com.itravel.cms.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class AbstractController {
    
	@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        
        NumberFormat floatFormat = new DecimalFormat(",##0.00");
        binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class,floatFormat, true));
        binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class,floatFormat, true));
    }

	protected List<String> parseIds(String ids) {
		String[] idArray = ids.split(",");
		return Arrays.asList(idArray);
	}
	
	protected InputStream saveFileAndGetInputStream(MultipartFile file,String fileName) throws IllegalStateException, IOException {
		File newFile = new File(fileName);
		file.transferTo(newFile);
		return new BufferedInputStream(FileUtils.openInputStream(newFile));
	}
	
	protected void saveFile(MultipartFile file,String fileName) throws IllegalStateException, IOException {
		File newFile = new File(fileName);
		file.transferTo(newFile);
	}
}
